package com.acxiom.bsh.service.impl;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.acxiom.bsh.constants.CommonConstant;
import com.acxiom.bsh.logger.LoggerManager;
import com.acxiom.bsh.pojo.ApiError;
import com.acxiom.bsh.pojo.ApiToken;
import com.acxiom.bsh.request.GetTokenRequest;
import com.acxiom.bsh.response.ApiResponse;
import com.acxiom.bsh.service.ApiService;
import com.acxiom.bsh.service.ApiTokenService;
import com.acxiom.bsh.util.CryptUtils;

@Service
public class ApiTokenServiceImpl implements ApiTokenService {
	
	@Autowired
	ApiService apiService;
	
	@Value("${tp.api.username}")
	private String username;
	
	@Value("${tp.api.password}")
	private String password;
	
	@Override
	public ApiToken getToken() {
		try {
			LoggerManager.getCommonLogger().info(String.format("u:%s,p:%s", username, password));
			GetTokenRequest request = new GetTokenRequest(username, CryptUtils.decrypt(password, CommonConstant.SECURITY_KEY));
			ApiResponse response = apiService.post("authentication/token", request);
			if (response != null && response.getMeta() != null && response.getMeta().isSuccess()) {
				@SuppressWarnings("unchecked")
				Map<String, Object> tokenMap = (Map<String, Object>)response.getData();
				ApiToken apiToken = new ApiToken();
				apiToken.setToken((String)tokenMap.get("token"));
				apiToken.setRefreshToken((String)tokenMap.get("refreshToken"));
				return apiToken;
			} else {
				String error = "No message";
				if (response != null && response.getMeta() != null && response.getMeta().getErrors() != null && response.getMeta().getErrors().size() >0) {
					ApiError apiError = response.getMeta().getErrors().get(0);
					error = String.format("code:[%d], msg:[%s]", apiError.getCode(), apiError.getMsg());
				}
				LoggerManager.getErrorLogger().error(String.format("Failed to get token : {%s}", error));
			}
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error(String.format("Failed to get token : {%s}", e.getMessage()));
		}
		return null;
	}

}
